{% load static %}
<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>智能家居 · 控制中心</title>
  <!-- Font Awesome 图标库 -->
  <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <style>
    /* ===== 新增背景设置 ===== */
    body {
      font-family:"Segoe UI",sans-serif;
      margin:0;
      min-height:100vh;
      /* 背景图片设置 */
      background: url('{% static "images/background.jpg" %}') no-repeat center center fixed;
      background-size: cover;
      position: relative;
    }
    /* 确保内容在遮罩层上方 */
    .wrapper {
      position: relative;
      z-index: 1;
      max-width:960px;
      margin:40px auto;
      background:#fff;
      padding:24px 32px;
      border-radius:16px;
      box-shadow:0 6px 18px rgba(0,0,0,.12);
    }

    /* ===== 保持原有样式不变 ===== */
    h1          {margin:0;color:#2563eb;display:flex;align-items:center;font-size:26px}
    h1 i        {margin-right:10px}
    .welcome-sub{margin-top:4px;color:#6b7280;font-size:14px}
    .section-title{font-size:18px;font-weight:600;display:flex;align-items:center;color:#374151}
    .section-title i{margin-right:8px}
    .preset-btns {display:flex;flex-wrap:wrap;gap:10px;margin-top:14px}
    .preset-btn  {padding:8px 14px;border:1px solid #e5e7eb;border-radius:8px;
                  background:#f9fafb;cursor:pointer;font-size:14px;transition:.2s}
    .preset-btn.active{background:#2563eb;color:#fff;border-color:#2563eb}
    #presetDesc  {margin-top:6px;color:#6b7280;font-size:13px}
    .room-list   {display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-top:16px}
    .room-btn    {padding:10px;background:#f3f4f6;border:none;border-radius:8px;
                  display:flex;align-items:center;justify-content:center;cursor:pointer}
    .room-btn.active{background:#2563eb;color:#fff}
    #deviceBox   {margin-top:16px}
    .device-card {border:1px solid #e5e7eb;border-radius:10px;padding:12px 16px;margin-bottom:12px;
                  display:flex;flex-direction:column;gap:8px}
    .device-meta {display:flex;align-items:center;justify-content:space-between;font-size:15px}
    .type-tag    {padding:1px 6px;border-radius:6px;font-size:11px;background:#e5e7eb;color:#374151}
    .device-state{font-size:13px;color:#6b7280}
    .status-btn {padding:4px 8px;font-size:12px;border:none;border-radius:4px;cursor:pointer;}
    .status-btn.online  {background:#22c55e;color:#fff;}
    .status-btn.offline {background:#ef4444;color:#fff;}
    .device-slider {display:flex;align-items:center;gap:8px}
    .nav         {margin-top:30px;display:flex;justify-content:center;gap:14px}
    .nav a       {display:flex;align-items:center;gap:6px;padding:8px 18px;border-radius:8px;
                  text-decoration:none;color:#fff;font-size:14px;opacity:0.7;transition:.2s}
    .nav a:hover {opacity:1}
    .nav .overview {background:#2563eb}
    .nav .detail   {background:#3b82f6}
    .nav .manage   {background:#10b981}
    .nav .messages     { background:#f59e0b; }
    .nav .logout   {background:#ef4444}
  </style>
</head>
<body>
<!-- 保持原有HTML内容不变 -->
<div class="wrapper">
  <!-- 顶部：欢迎 + 权限 -->
  <h1><i class="fas fa-home"></i>欢迎回家，<span id="welcomeName">—</span></h1>
  <div class="welcome-sub" id="welcomeSub">—</div>

  <!-- 预设模式 -->
  <div id="presetSection" style="margin-top:28px">
    <div class="section-title"><i class="fas fa-sliders-h"></i>预设参数</div>
    <div class="preset-btns" id="presetBtns"></div>
    <div id="presetDesc">选择一个模式来快速调整所有房间</div>
  </div>

  <!-- 房间按钮 -->
  <div id="roomSection" style="margin-top:34px">
    <div class="section-title"><i class="fas fa-door-closed"></i>房间控制</div>
    <div class="room-list" id="roomList"></div>
  </div>

  <!-- 设备卡片 -->
  <div id="deviceSection" style="margin-top:34px">
    <div class="section-title"><i class="fas fa-microchip"></i><span id="roomTitle">设备遥控</span></div>
    <div id="deviceBox">选择一个房间查看设备</div>
  </div>

  <!-- 底部导航 -->
  <div class="nav">
    <a href="/index/" class="overview"><i class="fas fa-tachometer-alt"></i>总览</a>
    <a href="/device_manage/"  class="manage"  id="btnManage" style="display:none"><i class="fas fa-tools"></i>设备管理</a>
    <a href="/monitor/messages/" class="messages"><i class="fas fa-envelope"></i>监控</a>
    <a href="#" class="logout" id="logoutBtn"><i class="fas fa-sign-out-alt"></i>登出</a>
  </div>
</div><!-- /.wrapper -->

<!-- 保持原有JavaScript不变 -->
<script>
/* ========= 预设模式常量（保持不变） ========= */
const modes = {
  default:{desc:'默认舒适模式，空调24℃、湿度50%、灯光300lux',   ac:24,  hum:50,  light:300},
  away   :{desc:'离家省电模式，所有设备下线',                   ac:0,   hum:0,   light:0},
  night  :{desc:'夜间安静，空调20℃、湿度45%、灯光10lux',       ac:20,  hum:45,  light:10},
  warm   :{desc:'暖房模式，空调27℃、湿度50%、灯光600lux',      ac:27,  hum:50,  light:600},
  sleep  :{desc:'睡眠模式，仅卧室灯光20lux，其他设备下线',       ac:0,   hum:0,   light:20},
  custom :{desc:'自定义模式：手动滑动设备后触发'}
};

/* ========= 全局变量 ========= */
let rooms            = [];           // [{room_id,name}]
let roomIdToName     = {};           // id->name
let devices          = [];           // 后端 /devices/
let devicesByRoom    = {};           // room_id -> [device]
let currentRoomId    = null;
let currentMode      = 'default';

const username        = localStorage.getItem('currentUser')   || '访客';
const role            = localStorage.getItem('userRole')      || '普通用户';
const permissionLevel = Number(localStorage.getItem('permissionLevel')||0);

/* ========= 页面初始化 ========= */
document.addEventListener('DOMContentLoaded', async () => {
  // 欢迎信息
  document.getElementById('welcomeName').textContent = username;
  document.getElementById('welcomeSub').textContent  =
      role==='管理员' ? '权限：管理员'
                      : `权限：${permissionLevel>=2?'查看／更改设备': permissionLevel===1?'仅查看设备':'无权限'}`;

  // 登出
  document.getElementById('logoutBtn').onclick = e=>{
    e.preventDefault(); localStorage.clear(); location.href='/';
  };

  // 权限可见性
  if (permissionLevel < 1) {
    document.getElementById('presetSection').style.display = 'none';
    document.getElementById('roomSection').style.display   = 'none';
    document.getElementById('deviceSection').style.display = 'none';
    document.querySelectorAll('.nav a.overview, .nav a.detail, .nav a.manage')
            .forEach(a=>a.style.display='none');
    return;
  }
  if (permissionLevel === 1) document.getElementById('presetSection').style.display='none';
  if (role==='管理员')      document.getElementById('btnManage').style.display='flex';

  renderPresetButtons();   // 先把按钮放好

  // 先拿房间，再拿设备
  await loadRooms();
  await loadDevices();
  renderRoomButtons();
});

/* ========= 通用 fetch ========= */
async function api(path,opt={}) {
  const res = await fetch(path,{...opt,headers:{'Content-Type':'application/json','Accept':'application/json'}});
  const txt=await res.text(); let data={}; try{data=txt?JSON.parse(txt):{}}catch{}
  if(!res.ok) throw Error(data.detail||data.message||res.statusText);
  return data;
}

/* ========= 房间列表 ========= */
async function loadRooms(){
  rooms = await api('/rooms/');
  roomIdToName = Object.fromEntries(rooms.map(r=>[r.room_id,r.name]));
}

/* ========= 设备列表 ========= */
async function loadDevices(){
  devices = await api('/devices/');
  devicesByRoom = devices.reduce((m,d)=>(m[d.room_id]=(m[d.room_id]||[]).concat(d),m),{});
}

/* ========= 预设按钮 ========= */
function renderPresetButtons(){
  const wrap=document.getElementById('presetBtns'); wrap.innerHTML='';
  Object.keys(modes).filter(k=>k!=='custom').forEach(k=>{
    wrap.insertAdjacentHTML('beforeend',`<button class="preset-btn ${k==='default'?'active':''}" data-mode="${k}">
      ${{default:'默认',away:'离家',night:'夜间',warm:'暖房',sleep:'睡眠'}[k]}</button>`);
  });
  wrap.onclick=e=>{
    const btn=e.target.closest('.preset-btn'); if(!btn)return;
    applyMode(btn.dataset.mode);
  };
}

/* ========= 应用模式 ========= */
async function applyMode(modeKey){
  currentMode=modeKey;
  document.querySelectorAll('.preset-btn').forEach(b=>b.classList.toggle('active',b.dataset.mode===modeKey));
  document.getElementById('presetDesc').textContent=modes[modeKey].desc;
  if(modeKey==='custom') return;

  // 找到卧室 room_id（用于 sleep 模式）
  const bedroomId = rooms.find(r=>r.name==='卧室')?.room_id;

  for(const dev of devices){
    let targetStatus='online', targetValue;
    if(modeKey==='away'){ targetStatus='offline'; }
    else if(modeKey==='sleep'){
      if(dev.room_id===bedroomId && dev.device_type==='灯光'){ targetValue=modes.sleep.light; }
      else{ targetStatus='offline'; }
    }else{
      targetValue = modes[modeKey][ dev.device_type==='空调'?'ac'
                                   :dev.device_type==='加湿器'?'hum'
                                   :'light'];
    }
    await api(`/devices/${dev.device_id}/`,{method:'PUT',body:JSON.stringify({status:targetStatus})});
    if(targetStatus==='online'){
      await api(`/devices/${dev.device_id}/control/`,{method:'POST',body:JSON.stringify({action:'set',value:targetValue})});
    }
  }
  await loadDevices();
  renderDeviceBox();
}

/* ========= 自定义模式 ========= */
function switchToCustomMode(){
  if(currentMode!=='custom'){
    currentMode='custom';
    document.querySelectorAll('.preset-btn').forEach(b=>b.classList.remove('active'));
    document.getElementById('presetDesc').textContent=modes.custom.desc;
  }
}

/* ========= 房间按钮 ========= */
function renderRoomButtons(){
  const box=document.getElementById('roomList'); box.innerHTML='';
  rooms.forEach((r,i)=>{
    box.insertAdjacentHTML('beforeend',`<button class="room-btn ${i===0?'active':''}" data-id="${r.room_id}">
       ${r.name}</button>`);
    if(i===0){ currentRoomId=r.room_id; }
  });
  box.onclick=e=>{
    const btn=e.target.closest('.room-btn'); if(!btn)return;
    document.querySelectorAll('.room-btn').forEach(b=>b.classList.toggle('active',b===btn));
    currentRoomId = Number(btn.dataset.id);
    document.getElementById('roomTitle').textContent=`${roomIdToName[currentRoomId]} · 设备遥控`;
    renderDeviceBox();
  };
  // 初次进来
  document.getElementById('roomTitle').textContent=`${roomIdToName[currentRoomId]} · 设备遥控`;
  renderDeviceBox();
}

/* ========= 单位助手 ========= */
function unitMap(type){ return type==='空调'?'℃': type==='加湿器'?'%':'lux'; }

/* ========= 设备卡片 ========= */
function renderDeviceBox(){
  const list=devicesByRoom[currentRoomId]||[];
  const box=document.getElementById('deviceBox');
  if(!list.length){ box.innerHTML='该房间暂无设备'; return; }
  box.innerHTML='';
  list.forEach(dev=>{
    const isOnline=dev.status==='online';
    const [minV,maxV] = dev.device_type==='空调'? [16,32]
                       : dev.device_type==='加湿器'? [30,90]
                       : dev.device_type==='灯光'? [0,1000] : [0,500];
    const val = dev.control_value ?? minV;
    const unit = unitMap(dev.device_type);
    box.insertAdjacentHTML('beforeend',`
      <div class="device-card" id="card-${dev.device_id}">
        <div class="device-meta">
          <span>${dev.device_name}</span>
          <span class="type-tag">${dev.device_type}</span>
        </div>
        <div class="device-actions">
          <span class="device-state">${isOnline?'在线':'离线'}</span>
          ${permissionLevel>=2?`
            <button class="status-btn ${isOnline?'online':'offline'}"
                    onclick="toggleStatus(event,'${dev.device_id}')">
              ${isOnline?'下线':'上线'}
            </button>`:''}
        </div>
        <div class="device-slider">
          <input type="range" min="${minV}" max="${maxV}" value="${val}"
                 ${isOnline&&permissionLevel>=2?
                   `oninput="switchToCustomMode();
                             this.nextElementSibling.textContent=this.value+'${unit}';
                             handleSlide('${dev.device_id}',this.value)"`:'disabled'}>
          <span>${val}${unit}</span>
        </div>
      </div>`);
  });
}

/* ========= 上下线 ========= */
async function toggleStatus(evt, id) {
  evt.stopPropagation();
  const card = document.getElementById(`card-${id}`);
  const cur = card.querySelector('.device-state').textContent;
  const next = cur === '在线' ? 'offline' : 'online';
  try {
    await api(`/devices/${id}/`, { method: 'PUT', body: JSON.stringify({ status: next }) });
    
    // 重新加载设备数据
    await loadDevices();
    
    // 重新渲染设备卡片
    renderDeviceBox();
    
    // 切换到自定义模式
    switchToCustomMode();

  } catch (e) {
    alert('切换状态失败：' + e.message);
  }
}

/* ========= 滑杆控制 ========= */
async function handleSlide(id,val){
  try{
    await api(`/devices/${id}/control/`,{method:'POST',body:JSON.stringify({action:'set',value:Number(val)})});
  }catch(e){ alert('下发失败：'+e.message); }
}
</script>
</body>
</html>